package ru.spbu.math.android.cbrf.charts;

import math.spbu.ru.historycharts.ChartFactory;
import math.spbu.ru.historycharts.ChartsView;
import ru.spbu.math.android.cbrf.R;
import ru.spbu.math.android.cbrf.view.WidgetProvider;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class ChartsActivity extends Activity {

	private String rateTypeId;
	private static ChartsView view;
	private DateDialog dateDialog;
	private DataProvider provider;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle extras = getIntent().getExtras();
		rateTypeId = extras.getString(WidgetProvider.RATE_TYPE_ID);
		Log.d("BNV ChartsActivity", "rateTypeId " + rateTypeId);

		try {
			provider = new DataProvider(this, rateTypeId);
		} catch (Exception e) {
			error();
		}

		view = ChartFactory.getTimeChartView(this, provider);
		setContentView(view);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, SET_DATE, 0, R.string.Set_Date);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		if (dateDialog == null)
			dateDialog = new DateDialog(this, provider);
		dateDialog.show();
		return true;
	}

	public static void repaintView() {
		view.repaint();
	}

	public void error() {
		Log.e("ChartsActivity", "Error, finish Activity");
		CharSequence text = "Error";
		Toast toast = Toast.makeText(ChartsActivity.this, text,
				Toast.LENGTH_SHORT);
		toast.show();
		finish();
	}

	public static View getView() {
		return view;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean ret = super.onKeyDown(keyCode, event);
		if (keyCode == 4) {
			view = null;
			finish();
		}
		return ret;
	}

	private final int SET_DATE = 3;

}